package com.wizz.trade.information.controller;

import com.wizz.trade.common.PageVo;
import com.wizz.trade.information.dto.StaDto;
import com.wizz.trade.information.dto.page.StaPageDto;
import com.wizz.trade.information.entity.Sta;
import com.wizz.trade.information.service.StaService;
import com.wizz.trade.common.ResponseResult;
import com.wizz.trade.common.constant.StatusCode;
import com.wizz.trade.information.vo.StaVo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 资料模块/仓储协议
 */
@RestController
@RequestMapping("/sta")
public class StaController {

    @Resource
    private StaService staService;

    /**
     * 添加操作
     *
     * @param staDto
     * @return
     */
    @PostMapping
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")
    public ResponseResult addSta(@RequestBody StaDto staDto) {
        Sta sta = new Sta();
        BeanUtils.copyProperties(staDto, sta);
        staService.addSta(sta);
        return new ResponseResult<>(StatusCode.OK, "添加成功");
    }

    /**
     * 更新（编辑）操作
     *
     * @param staDto
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")
    public ResponseResult updateSta(@RequestBody StaDto staDto, @PathVariable("id") Integer id) {
        Sta sta = new Sta();
        BeanUtils.copyProperties(staDto, sta);
        sta.setId(id);
        staService.updateSta(sta);
        return new ResponseResult<>(StatusCode.OK, "修改成功");
    }

    /**
     * 删除（撤销）操作
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")
    public ResponseResult deleteSta(@PathVariable("id") Integer id) {
        staService.deleteSta(id);
        return new ResponseResult<>(StatusCode.OK, "删除成功");
    }

    /**
     * 分页刷新、条件查询
     * @param staPageDto
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('仓储协议、费率登记')")
    public ResponseResult<PageVo<StaVo>> list(StaPageDto staPageDto){
        PageVo<Sta> rawPage = staService.getPage(staPageDto);
        List<Sta> data = rawPage.getData();
        List<StaVo> dataVo = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            StaVo  staVo = new StaVo();
            BeanUtils.copyProperties(data.get(i), staVo);
            dataVo.add(staVo);
        }
        return new ResponseResult<>(StatusCode.OK, new PageVo<>(rawPage.getPages(), rawPage.getTotal(), dataVo));
    }
}
